const express = require("express");
const bodyParser = require("body-parser"); // 处理json请求
const mutiparty = require("multiparty"); // 处理multipart/form-data请求
const fse = require("fs-extra"); // 文件操作库
const cors = require("cors");
const path = require("path");
const app = express();
let fs = require("fs"); // 文件操作库
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // 处理url编码的请求
app.use(express.static(path.join(__dirname, "./public"))); // 静态资源目录可以直接访问
app.get("/cs", (req, res) => {
  res.send("hello");
});
let UPLOAD_DIR = path.join(__dirname, "./public/uploads"); //临时存储目录
app.post("/upload", (req, res) => {
  const form = new mutiparty.Form({ uploadDir: "temp" }); 
  form.parse(req); // 解析请求
  form.on("file", async (name, chunk) => {
    try {
      console.log(name, chunk.path, chunk.originalFilename, "name");
      let chunkDir = `${UPLOAD_DIR}/${chunk.originalFilename.split(".")[0]}`; // 切片目录
      if (!fse.existsSync(chunkDir)) {
        // 创建切片目录
        await fse.mkdirs(chunkDir);
      }
      var dPath = path.join(chunkDir, chunk.originalFilename.split(".")[1]); // 切片文件路径
      await fse.move(chunk.path, dPath, { overwrite: true }); // 移动切片文件到切片目录
      res.send("上传成功");
    } catch (err) {
      res.send("上传失败");
    }
  });
});
//合并切片
app.post("/merge", async function (req, res) {

  let name = req.body.name; //拿到文件名
  let fname = name.split(".")[0]; //拿到文件名
  let ext = name.split(".")[1];  //拿到文件扩展名
  let chunDir = path.join(UPLOAD_DIR, fname); //临时存储切片目录
  let chunks = await fse.readdir(chunDir); // 读取切片目录

  chunks
    .sort((a, b) => a - b)
    .map((chunkPath) => {
      fs.appendFileSync(  // 合并切片文件
        path.join(__dirname, "./temp/" + name), // 合并后的文件名及路径
        fs.readFileSync(`${chunDir}/${chunkPath}`) // 插入切片文件内容
      );
    });
  fse.removeSync(chunDir); // 删除切片目录
  res.send("合并成功");
});
app.listen(3000, () => {
  console.log("http://localhost:3220/public/index.html");
});
